import { resources, Asset, __private, AssetManager, assetManager } from 'cc';

export class ResMgr {
    private static _inst: ResMgr;
    public static get inst(): ResMgr {
        if (this._inst == null) {
            this._inst = new ResMgr();
        }
        return this._inst;
    }

    constructor() {

    }

    public load<T extends Asset>(paths: string,
        type: __private._types_globals__Constructor<T> | null,
        onProgress: ((finished: number, total: number, item: AssetManager.RequestItem) => void) | null,
        onComplete: ((err: Error | null, data: T) => void) | null)
        : void {
        let pathArray = paths.split("/");
        let bundleName = pathArray[0];
        let resUrl = paths.substring(bundleName.length + 1, paths.length);
        let bundle = assetManager.getBundle(paths);
        if (null != bundle) {
            bundle.load(resUrl, onComplete);
        } else {
            assetManager.loadBundle(bundleName, (err, bundle) => {
                if (err) {
                    console.log("try load from resources");
                    resources.load<T>(resUrl, type, onProgress, onComplete);
                    return;
                }
                bundle.load(resUrl, (err, d: any) => {
                    if (err) {
                        console.log("try load from resources");
                        resources.load<T>(resUrl, type, onProgress, onComplete);
                        return;
                    }
                    onComplete(err, d);
                });
            });
        }
    }
}